#pragma once
#include <iostream>
#include <sys/epoll.h>
#include "Log.h"
#include "comm.h"

using namespace LogMudule;
namespace EpollMoudle
{
    class Epoller
    {
    public:
        Epoller()
            : _epdf(-1)
        {
        }
        void Init()
        {
            _epdf = epoll_create(256);
            if (_epdf < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_create error";
                exit(EPOLL_CREATE_ERR);
            }
            LOG(LogLevel::DEBUG) << "epoll_create success" << _epdf;
        }
        int Wait(struct epoll_event ev[], int num, int timeout)
        {
            int n = epoll_wait(_epdf, ev, num, timeout);
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_wait error";
            }
            return n;
        }
        void Ctrl(int sockfd, int event, int flag)
        {
            struct epoll_event ev;
            ev.data.fd = sockfd;
            ev.events = event;
            int n = epoll_ctl(_epdf, flag, sockfd, &ev);
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl_add error";
            }
        }
        void ADD(int sockfd, int event)
        {
            Ctrl(sockfd, event, EPOLL_CTL_ADD);
        }
        void Update(int sockfd, int event)
        {
            Ctrl(sockfd, event, EPOLL_CTL_MOD);
        }
        void Detele(int sockfd)
        {
            int n = epoll_ctl(_epdf, EPOLL_CTL_DEL, sockfd, nullptr);
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl error";
            }
        }

    private:
        int _epdf;
    };
}